<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>员工管理系统</title>
    <!-- 引入LayUI资源 -->
    <link rel="stylesheet" href="js/layui/new/layui-new.css">
    <style>
        /* 按钮组间距统一 */
        .layui-btn-group { margin-bottom: 10px; }
        .layui-btn-group .layui-btn { margin-right: 8px; }

        /* 状态标签样式（与LayUI配色统一） */
        .status-tag {
            padding: 2px 8px;
            border-radius: 4px;
            color: #fff;
            display: inline-block; /* 避免文字挤压 */
        }
        .enable-tag { background-color: #5FB878; } /* 成功色（更贴合LayUI） */
        .disable-tag { background-color: #FFB800; } /* 警告色（扩展场景） */

        /* 表单样式优化 */
        .form-container {
            padding: 20px;
            height: 100%;
            box-sizing: border-box;
            overflow-y: auto;
        }
        .layui-form-item {
            margin-bottom: 15px;
        }
        .layui-form-label {
            width: 100px;
        }
        .layui-input-block {
            margin-left: 130px;
        }
        .form-actions {
            margin-top: 20px;
            text-align: right;
        }
    </style>
</head>
<body class="layui-layout-body" style="padding: 15px;">

<!-- 操作栏：用LayUI按钮组包裹，强制布局规整 -->
<div class="layui-btn-group">
    <button class="layui-btn layui-btn-normal" id="btnAdd">添加成员</button>
    <button class="layui-btn layui-btn-danger" id="btnBatchDel">批量删除</button>
</div>

<!-- 员工表格：重点优化列宽和样式 -->
<table class="layui-table" id="employeeTable" lay-filter="employeeTable"></table>

<!-- 操作按钮模板：保持原逻辑，样式由LayUI控制 -->
<script type="text/html" id="tplOperation">
    <a class="layui-btn layui-btn-sm layui-btn-normal" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-sm layui-btn-warm" lay-event="changePwd">修改密码</a>
    <a class="layui-btn layui-btn-sm layui-btn-danger" lay-event="del">删除</a>
</script>

<!-- 引入LayUI核心 -->
<script src="js/layui/new/layui-new.js"></script>
<script>
    layui.use(['table', 'layer', 'form'], function(){
        var table = layui.table;
        var layer = layui.layer;
        var form = layui.form;
        var $ = layui.$;

        // 1. 表格渲染：重点优化列宽和样式适配
        table.render({
            elem: '#employeeTable',
            url: '/employee/list', // 实际接口地址
            method: 'GET',
            page: true,               // 开启分页
            limit: 10,                // 每页条数
            limits: [10,20,30],       // 分页选项
            request: {
                pageName: 'page',     // 与后端统一分页参数
                limitName: 'limit'
            },
            parseData: function(res){ // 适配后端数据结构
                return {
                    "code": 0,        // 强制返回成功码
                    "data": res.records || [], // 数据列表
                    "count": res.total || 0   // 总条数
                };
            },
            height: 'full-200', // 自动填满页面高度
            cols: [[
                {type: 'checkbox', fixed: 'left'}, // 复选框固定左侧
                {title: '序号', type: 'numbers', width: 60, align: 'center'},
                {title: '姓名', field: 'actualName', minWidth: 120},
                {title: '性别', field: 'gender', minWidth: 100},
                {title: '登录账号', field: 'loginName', minWidth: 150},
                {title: '手机号', field: 'phone', minWidth: 150},
                {title: '邮箱', field: 'email', minWidth: 220}, // 邮箱较长，加宽
                {title: '部门', field: 'department', minWidth: 150},
                {title: '状态', field: 'idDisabled', minWidth: 100, templet: function(d){
                        // 状态标签化：与LayUI配色统一
                        var tagCls = d.idDisabled === '启用' ? 'enable-tag' : 'disable-tag';
                        return '<span class="status-tag ' + tagCls + '">' + d.idDisabled + '</span>';
                    }},
                {title: '职务', field: 'position', minWidth: 150},
                {title: '操作', width: 260, align: 'center', templet: '#tplOperation'}
            ]],
            skin: 'line',  // 线条风格
            even: true,    // 隔行变色
            size: 'lg'     // 表格尺寸放大
        });

        // 2. 添加成员表单构建函数
        function buildAddForm() {
            return `
                <div class="form-container">
                    <form class="layui-form" lay-filter="addEmployeeForm" id="addEmployeeForm">
                        <input type="hidden" name="id">

                        <div class="layui-form-item">
                            <label class="layui-form-label">姓名 <span style="color:red">*</span></label>
                            <div class="layui-input-block">
                                <input type="text" name="actualName" lay-verify="required" placeholder="请输入姓名" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">性别</label>
                            <div class="layui-input-block">
                                <input type="radio" name="gender" value="男" title="男" checked>
                                <input type="radio" name="gender" value="女" title="女">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">登录账号 <span style="color:red">*</span></label>
                            <div class="layui-input-block">
                                <input type="text" name="loginName" lay-verify="required|account" placeholder="请输入登录账号" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">初始密码 <span style="color:red">*</span></label>
                            <div class="layui-input-block">
                                <input type="password" name="password" lay-verify="required|pass" placeholder="请设置初始密码" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">手机号 <span style="color:red">*</span></label>
                            <div class="layui-input-block">
                                <input type="text" name="phone" lay-verify="required|phone" placeholder="请输入手机号" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">邮箱</label>
                            <div class="layui-input-block">
                                <input type="text" name="email" lay-verify="email" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">部门 <span style="color:red">*</span></label>
                            <div class="layui-input-block">
                                <select name="department" lay-verify="required">
                                    <option value="">请选择部门</option>
                                    <option value="西安研发部">西安研发部</option>
                                    <option value="北京研发部">北京研发部</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">职务 <span style="color:red">*</span></label>
                            <div class="layui-input-block">
                                <select name="position" lay-verify="required">
                                    <option value="">请选择职位</option>
                                    <option value="软件开发">软件开发</option>
                                    <option value="测试">测试</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-block">
                                <input type="radio" name="idDisabled" value="启用" title="启用" checked>
                                <input type="radio" name="idDisabled" value="禁用" title="禁用">
                            </div>
                        </div>

                        <div class="form-actions">
                            <button type="button" class="layui-btn layui-btn-primary" id="cancelAdd">取消</button>
                            <button type="submit" class="layui-btn" lay-submit lay-filter="submitAdd">保存</button>
                        </div>
                    </form>
                </div>
            `;
        }

        // 3. 事件逻辑
        // --- 添加成员 ---
        $('#btnAdd').on('click', function(){
            var addIndex = layer.open({
                type: 1,               // 页面层
                title: '添加成员',      // 弹窗标题
                area: ['550px', '650px'], // 弹窗尺寸
                offset: 'right',       // 从右侧滑出
                shade: 0.3,            // 遮罩透明度
                shadeClose: true,      // 点击遮罩关闭弹窗
                content: buildAddForm(), // 动态生成表单HTML
                success: function(){
                    // 渲染表单
                    form.render(null, 'addEmployeeForm');

                    // 取消按钮事件
                    $('#cancelAdd').on('click', function() {
                        layer.close(addIndex);
                    });
                }
            });
        });

        // --- 表单提交 ---
        form.on('submit(submitAdd)', function(data){
            // 提交到后端
            $.ajax({
                url: '/employee/add',  // 添加员工的API地址
                type: 'POST',
                data: data.field,
                dataType: 'json',
                success: function(res) {
                    if (res.code === 1) {
                        layer.msg(res.message || '添加成功', {icon: 1,time: 1000}, function() {
                            layer.closeAll('page');
                            table.reload('employeeTable');
                        });
                    } else {
                        layer.msg('添加失败：' + (res.message || '未知错误'), {icon: 2,time: 1000});
                    }
                },
                error: function() {
                    layer.msg('网络异常，请稍后重试', {icon: 2});
                }
            });
            return false; // 阻止表单默认提交
        });

        // --- 批量删除 ---
        $('#btnBatchDel').on('click', function(){
            var checkStatus = table.checkStatus('employeeTable');
            if(checkStatus.data.length === 0){
                layer.msg('请选择需删除的员工', {icon: 2,time: 1000});
                return;
            }
            layer.confirm('确定删除选中的 '+checkStatus.data.length+' 名员工？操作不可恢复！', {
                icon: 3, title: '危险操作'
            }, function(index){
                var loginNames = checkStatus.data.map(item => item.loginName);

                $.ajax({
                    url: '/employee/batchDelete',
                    type: 'POST',
                    data: JSON.stringify(loginNames), // 发送JSON格式
                    contentType: 'application/json; charset=utf-8', // 明确指定字符集
                    dataType: 'json', // 期望返回JSON
                    processData: false, // 防止jQuery处理数据
                    success: function(res){
                        if(res.code === 1){
                            layer.msg('删除成功', {icon: 1,time: 1000}, function(){
                                table.reload('employeeTable');
                            });
                        } else {
                            layer.msg('删除失败：'+res.message, {icon: 2});
                        }
                    },
                    error: function(xhr, status, error){
                        console.log('删除错误:', xhr.responseText);
                        layer.msg('网络异常，请重试', {icon: 2,time: 1000});
                    }
                });
                layer.close(index);
            });
        });


        // --- 行操作（编辑/删除/修改密码） ---
        table.on('tool(employeeTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                location.href = 'employee-edit.html?loginName='+data.loginName;
            } else if(obj.event === 'changePwd'){
                // 修改密码功能
                showChangePasswordDialog(data);
            } else if(obj.event === 'del'){
                layer.confirm('确定删除【'+data.actualName+'】？', {icon: 3}, function(index){
                    $.ajax({
                        url: '/employee/delete',  // 修正API路径
                        type: 'POST',
                        data: {loginName: data.loginName},  // 修正参数名
                        success: function(res){
                            if(res.code === 1){  // 修正成功码判断
                                obj.del(); // 删除当前行
                                layer.msg('删除成功', {icon: 1});
                            } else {
                                layer.msg('删除失败：'+res.message, {icon: 2});  // 修正错误信息字段
                            }
                        },
                        error: function(){
                            layer.msg('网络异常，请重试', {icon: 2});
                        }
                    });
                    layer.close(index);
                });
            }
        });

        // 显示修改密码对话框
        function showChangePasswordDialog(employee) {
            var changePwdIndex = layer.open({
                type: 1,
                title: '修改密码 - ' + employee.actualName,
                area: ['450px', '400px'],
                offset: 'center',
                shade: 0.3,
                shadeClose: true,
                content: `
                    <div class="form-container">
                        <form class="layui-form" lay-filter="changePasswordForm" id="changePasswordForm">
                            <input type="hidden" name="loginName" value="${employee.loginName}">

                            <div class="layui-form-item">
                                <label class="layui-form-label">员工姓名</label>
                                <div class="layui-input-block">
                                    <input type="text" value="${employee.actualName}" class="layui-input" readonly style="background-color: #f5f5f5;">
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">登录账号</label>
                                <div class="layui-input-block">
                                    <input type="text" value="${employee.loginName}" class="layui-input" readonly style="background-color: #f5f5f5;">
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">新密码 <span style="color:red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="password" name="newPassword" lay-verify="required|pass" placeholder="请输入新密码" autocomplete="off" class="layui-input">
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">确认密码 <span style="color:red">*</span></label>
                                <div class="layui-input-block">
                                    <input type="password" name="confirmPassword" lay-verify="required|confirmPassword" placeholder="请再次输入新密码" autocomplete="off" class="layui-input">
                                </div>
                            </div>

                            <div class="form-actions">
                                <button type="button" class="layui-btn layui-btn-primary" id="cancelChangePwd">取消</button>
                                <button type="submit" class="layui-btn" lay-submit lay-filter="submitChangePwd">确认修改</button>
                            </div>
                        </form>
                    </div>
                `,
                success: function(){
                    // 渲染表单
                    form.render(null, 'changePasswordForm');

                    // 取消按钮事件
                    $('#cancelChangePwd').on('click', function() {
                        layer.close(changePwdIndex);
                    });
                }
            });
        }

        // 修改密码表单提交
        form.on('submit(submitChangePwd)', function(data){
            // 验证两次密码是否一致
            if(data.field.newPassword !== data.field.confirmPassword) {
                layer.msg('两次输入的密码不一致', {icon: 2, time: 2000});
                return false;
            }

            // 显示加载状态
            var loadIndex = layer.load(1, {shade: [0.3, '#000']});

            // 提交到后端
            $.ajax({
                url: '/employee/changePassword',  // 修改密码的API地址
                type: 'POST',
                data: {
                    loginName: data.field.loginName,
                    newPassword: data.field.newPassword
                },
                dataType: 'json',
                success: function(res) {
                    layer.close(loadIndex);
                    if (res.code === 1) {
                        layer.msg(res.message || '密码修改成功', {icon: 1, time: 1500}, function() {
                            layer.closeAll('page');
                        });
                    } else {
                        layer.msg('密码修改失败：' + (res.message || '未知错误'), {icon: 2, time: 2000});
                    }
                },
                error: function() {
                    layer.close(loadIndex);
                    layer.msg('网络异常，请稍后重试', {icon: 2});
                }
            });
            return false; // 阻止表单默认提交
        });

        // 自定义验证规则
        form.verify({
            account: function(value) {
                if (value.length < 5) {
                    return '登录账号至少5个字符';
                }
                if (!/^[a-zA-Z0-9_]{5,}$/.test(value)) {
                    return '登录账号只能包含字母、数字和下划线';
                }
            },
            pass: [
                /^[\S]{6,12}$/
                ,'密码必须6到12位，且不能出现空格'
            ],
            confirmPassword: function(value, item) {
                var password = $('input[name=newPassword]').val();
                if (value !== password) {
                    return '两次输入的密码不一致';
                }
            }
        });
    });
</script>
</body>
</html>
